
#include <json/json.h>
#include <iostream>
#include <sstream>
#include <memory>
#include "mqtt_parse.h"
#include <ifaddrs.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <cstring>
#include <string>
#include <json/json.h>
#include <ctime>
#include "zlog_app.h"
#include "app_main.h"

enum class PollutionStatus : uint32_t
{
    UNCONTAMINATED = 14,      // 未污染
    CONTAMINATED = 4,         // 污染（C1门、CPO等单步测量设备）
    SEVERE_CONTAMINATION = 5, // 严重污染
    RSP_DISABLED = 255        // RSP禁用
};
// 旧的探测器状态
enum class DetectorStatus : uint16_t
{
    // 故障状态
    COMMUNICATION_FAULT = 10,   // 通讯故障
    LOW_BACKGROUND_FAULT = 11,  // 低本底故障
    HIGH_BACKGROUND_FAULT = 12, // 高本底故障
    HIGH_VOLTAGE_FAULT = 13,    // 高压故障

    RSP_ADJUSTING_HIGH_VOLTAGE = 16, // RSP正在调整高压
    RSP_ADJUSTING_STATE = 17,        // RSP正在调整工作状态
    RSP_HIGH_VOLTAGE_ERROR = 18,     // RSP高压误差过大
    RSP_NO_RESPONSE = 19,            // RSP无响应
    RSP_NOT_USER = 255,              // RSP 未使用
};
// 新探测器状态2025-09-30
enum class NewDetectorStatus : uint32_t
{
    NULLL = 0,
    BACKGROUND_MONITORING = 1U << 0, // 本底监测
    MEASURING = 1 << 1,              // 测量（C1、CPO等单步设备）

    RSP_ADJUSTING_HV = 1U << 2,       // RSP正在调整高压
    RSP_NO_RESPONSE = 1U << 3,        // RSP正在调整工作状态
    RSP_HV_ERROR_TOO_LARGE = 1U << 4, // RSP高压误差过大

    // 故障类状态
    COMMUNICATION_FAULT = 1U << 5,   // 通讯故障
    LOW_BACKGROUND_FAULT = 1U << 6,  // 低本底故障
    HIGH_BACKGROUND_FAULT = 1U << 7, // 高本底故障
    HIGH_VOLTAGE_FAULT = 1U << 8,    // 高压故障

    POLLUTED_ALPHA = 1U << 9,            // alpha污染
    POLLUTED_BETA = 1U << 10,            // beta污染
    POLLUTED_GAMMA = 1U << 11,           // gamma污染
    SERIOUSLY_POLLUTED_ALPHA = 1U << 12, // 严重污染alpha
    SERIOUSLY_POLLUTED_BETA = 1U << 13,  // 严重污染beta
    SERIOUSLY_POLLUTED_GAMMA = 1U << 14, // 严重污染gamma
    NOT_POLLUTED = 1U << 15,             // 未污染
    RSP_DISABLED = 1U << 31,             // RSP禁用

};

// 函数：获取指定网卡的 IPv4 地址
static std::string getLocalIPAddress(void)
{
    struct ifaddrs *ifaddrs_ptr = nullptr;
    // 获取本地 IPv4 地址
    const std::string interface = get_app_config_ptr()->cfg.ethernet_card_name;

    // 获取所有网络接口信息
    if (getifaddrs(&ifaddrs_ptr) == -1)
    {
        zlog_warn(zlog_get_category(ZLOG_CAG_ALL), "getifaddrs failed");
        return "";
    }

    std::string ip_addr;

    for (struct ifaddrs *ifa = ifaddrs_ptr; ifa != nullptr; ifa = ifa->ifa_next)
    {
        if (ifa->ifa_addr == nullptr)
            continue;

        // 检查是否为 IPv4 协议
        if (ifa->ifa_addr->sa_family == AF_INET)
        {
            // 检查接口名称是否匹配
            if (interface.empty() || ifa->ifa_name == interface)
            {
                struct sockaddr_in *addr_in = (struct sockaddr_in *)ifa->ifa_addr;
                char buffer[INET_ADDRSTRLEN];
                inet_ntop(AF_INET, &(addr_in->sin_addr), buffer, INET_ADDRSTRLEN);
                ip_addr = std::string(buffer);
                break; // 找到就退出
            }
        }
    }

    freeifaddrs(ifaddrs_ptr); // 释放内存

    if (ip_addr.empty())
    {
        zlog_warn(zlog_get_category(ZLOG_CAG_ALL), "Could not find IP address for interface: %s", interface.c_str());
    }

    return ip_addr;
}

// 函数：获取当前本地时间，格式化为 "YYYY-MM-DD HH:MM:SS"
static std::string getCurrentTimeFormatted()
{
    std::time_t now = std::time(nullptr);
    std::tm *localTime = std::localtime(&now);

    char buffer[20]; // "YYYY-MM-DD HH:MM:SS" 需要 19 字符 + \0
    std::strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", localTime);

    return std::string(buffer);
}

// 从 JSON 字符串加载到结构体
bool parse_heart_msg(struct DeviceHeartbeat &config, const std::string &json_string)
{
    Json::Value root;
    Json::CharReaderBuilder builder;
    std::string errs;

    // 使用字符串流解析 JSON
    std::istringstream iss(json_string);

    if (!parseFromStream(builder, iss, &root, &errs))
    {

        zlog_warn(zlog_get_category(ZLOG_CAG_MQTT), "json parse error");
        return false;
    }

    // 逐字段读取（带类型检查）
    if (root.isMember("ProtocolID") && root["ProtocolID"].isString())
    {
        config.ProtocolID = root["ProtocolID"].asString();
    }
    else
    {
        zlog_warn(zlog_get_category(ZLOG_CAG_MQTT), "ProtocolID is not string or menber not exist");
    }

    if (root.isMember("DevType") && root["DevType"].isInt())
    {
        config.DevType = root["DevType"].asInt();
    }
    else
    {
        zlog_warn(zlog_get_category(ZLOG_CAG_MQTT), "DevType is not int or menber not exist");
    }

    if (root.isMember("DevIP") && root["DevIP"].isString())
    {
        config.DevIP = root["DevIP"].asString();
    }
    else
    {
        zlog_warn(zlog_get_category(ZLOG_CAG_MQTT), "DevIP is not string or menber not exist");
    }

    if (root.isMember("HeartTime") && root["HeartTime"].isString())
    {
        config.HeartTime = root["HeartTime"].asString();
    }
    else
    {
        zlog_warn(zlog_get_category(ZLOG_CAG_MQTT), "HeartTime is not string or menber not exist");
    }

    if (root.isMember("HeartInterval") && root["HeartInterval"].isInt())
    {
        config.HeartInterval = root["HeartInterval"].asInt();
    }
    else
    {
        zlog_warn(zlog_get_category(ZLOG_CAG_MQTT), "HeartInterval is not int or menber not exist");
    }

    if (root.isMember("TestNum") && root["TestNum"].isInt())
    {
        config.TestNum = root["TestNum"].asInt();
    }
    else
    {
        zlog_warn(zlog_get_category(ZLOG_CAG_MQTT), "TestNum is not int or menber not exist");
    }

    if (root.isMember("AlarmNum") && root["AlarmNum"].isInt())
    {
        config.AlarmNum = root["AlarmNum"].asInt();
    }
    else
    {
        zlog_warn(zlog_get_category(ZLOG_CAG_MQTT), "AlarmNum is not int or menber not exist");
    }

    return true;
}

// 构建 JSON 字符串（只包含目标字段，且 HeartTime → Time）
std::string build_heartbeat_json(const DeviceHeartbeat &hb)
{
    Json::Value root;
    root["ProtocolID"] = hb.ProtocolID;
    root["DevType"] = hb.DevType;
    root["DevIP"] = getLocalIPAddress();      // 获取本机 IP 地址
    root["Time"] = getCurrentTimeFormatted(); // 字段重命名
    root["HeartInterval"] = hb.HeartInterval;

    // 使用 FastWriter 生成紧凑 JSON（无缩进）
    Json::StreamWriterBuilder builder;
    // builder["indentation"] = ""; // 空字符串表示不换行
    builder["indentation"] = "  "; // 2 spaces
    std::unique_ptr<Json::StreamWriter> writer(builder.newStreamWriter());
    std::ostringstream os;
    writer->write(root, &os);
    return os.str();
}

// 将字符串按分隔符 '/' 分割，存入 vector
std::vector<std::string> split_topic(const std::string &topic, char delimiter)
{
    std::vector<std::string> parts;
    std::stringstream ss(topic);
    std::string part;

    while (std::getline(ss, part, delimiter))
    {
        if (!part.empty())
        { // 可选：跳过空字符串
            parts.push_back(part);
        }
    }

    return parts;
}
#include <json/json.h>
#include <iostream>
#include <sstream>

/**
 * @brief 解析 JSON 中的报警阈值配置，填充到 AlarmThresholdConfig 结构体
 * @param config 输出参数：保存解析后的阈值配置
 * @param json_str 输入的 JSON 字符串
 * @return 成功返回 true，失败返回 false
 */
bool load_alarm_threshold_from_json(AlarmThresholdConfig &config, const std::string &json_str)
{
    Json::Value root;
    Json::CharReaderBuilder builder;
    std::string errs;

    std::istringstream iss(json_str);
    if (!parseFromStream(builder, iss, &root, &errs))
    {
        zlog_warn(zlog_get_category(ZLOG_CAG_MQTT), "json parse error");
        return false;
    }

    try
    {
        // 提取字段并赋值（带类型检查）
        if (root.isMember("AlarmMode") && root["AlarmMode"].isInt())
        {
            config.alarm_mode = root["AlarmMode"].asInt();
        }
        else
        {
            zlog_warn(zlog_get_category(ZLOG_CAG_MQTT), "AlarmMode is not int");
        }

        if (root.isMember("StaticGammaThreshold") && root["StaticGammaThreshold"].isDouble())
        {
            config.static_gamma_threshold = static_cast<float>(root["StaticGammaThreshold"].asFloat());
        }
        else
        {
            zlog_warn(zlog_get_category(ZLOG_CAG_MQTT), "StaticGammaThreshold is not double");
        }

        if (root.isMember("StaticBetaThreshold") && root["StaticBetaThreshold"].isDouble())
        {
            config.static_beta_threshold = static_cast<float>(root["StaticBetaThreshold"].asFloat());
        }
        else
        {
            zlog_warn(zlog_get_category(ZLOG_CAG_MQTT), "StaticBetaThreshold is not double");
        }

        if (root.isMember("StaticAlphaThreshold") && root["StaticAlphaThreshold"].isDouble())
        {
            config.static_alpha_threshold = static_cast<float>(root["StaticAlphaThreshold"].asFloat());
        }
        else
        {
            zlog_warn(zlog_get_category(ZLOG_CAG_MQTT), "StaticAlphaThreshold is not double");
        }

        if (root.isMember("StaticGammaSevere") && root["StaticGammaSevere"].isDouble())
        {
            config.static_gamma_severe = static_cast<float>(root["StaticGammaSevere"].asFloat());
        }
        else
        {
            zlog_warn(zlog_get_category(ZLOG_CAG_MQTT), "StaticGammaSevere is not double");
        }

        if (root.isMember("StaticBetaSevere") && root["StaticBetaSevere"].isDouble())
        {
            config.static_beta_severe = static_cast<float>(root["StaticBetaSevere"].asFloat());
        }
        else
        {
            zlog_warn(zlog_get_category(ZLOG_CAG_MQTT), "StaticBetaSevere is not double");
        }

        if (root.isMember("StaticAlphaSevere") && root["StaticAlphaSevere"].isDouble())
        {
            config.static_alpha_severe = static_cast<float>(root["StaticAlphaSevere"].asFloat());
        }
        else
        {
            zlog_warn(zlog_get_category(ZLOG_CAG_MQTT), "StaticAlphaSevere is not double");
        }

        if (root.isMember("DynamicGammaCoff") && root["DynamicGammaCoff"].isDouble())
        {
            config.dynamic_gamma_coff = static_cast<float>(root["DynamicGammaCoff"].asFloat());
        }
        else
        {
            zlog_warn(zlog_get_category(ZLOG_CAG_MQTT), "DynamicGammaCoff is not double or menber not exist");
        }

        if (root.isMember("DynamicBetaCoff") && root["DynamicBetaCoff"].isDouble())
        {
            config.dynamic_beta_coff = static_cast<float>(root["DynamicBetaCoff"].asFloat());
        }
        else
        {
            zlog_warn(zlog_get_category(ZLOG_CAG_MQTT), "DynamicBetaCoff is not double or menber not exist");
        }

        if (root.isMember("DynamicAlphaCoff") && root["DynamicAlphaCoff"].isDouble())
        {
            config.dynamic_alpha_coff = static_cast<float>(root["DynamicAlphaCoff"].asFloat());
        }
        else
        {
            zlog_warn(zlog_get_category(ZLOG_CAG_MQTT), "DynamicAlphaCoff is not double or menber not exist");
        }

        if (root.isMember("DynamicGammaSevereCoff") && root["DynamicGammaSevereCoff"].isDouble())
        {
            config.dynamic_gamma_severe_coff = static_cast<float>(root["DynamicGammaSevereCoff"].asFloat());
        }
        else
        {
            zlog_warn(zlog_get_category(ZLOG_CAG_MQTT), "DynamicGammaSevereCoff is not double or menber not exist");
        }

        if (root.isMember("DynamicBetaSevereCoff") && root["DynamicBetaSevereCoff"].isDouble())
        {
            config.dynamic_beta_severe_coff = static_cast<float>(root["DynamicBetaSevereCoff"].asFloat());
        }
        else
        {
            zlog_warn(zlog_get_category(ZLOG_CAG_MQTT), "DynamicBetaSevereCoff is not double or menber not exist");
        }

        if (root.isMember("DynamicAlphaSevereCoff") && root["DynamicAlphaSevereCoff"].isDouble())
        {
            config.dynamic_alpha_severe_coff = static_cast<float>(root["DynamicAlphaSevereCoff"].asFloat());
        }
        else
        {
            zlog_warn(zlog_get_category(ZLOG_CAG_MQTT), "DynamicAlphaSevereCoff is not double or menber not exist");
        }
    }
    catch (const std::exception &e)
    {
        zlog_warn(zlog_get_category(ZLOG_CAG_MQTT), "数据解析异常");
        return false;
    }

    return true;
}

// 函数：构建 JSON 字符串，Time 使用当前本地时间
std::string build_time_sync_json()
{
    Json::Value root;
    root["ProtocolID"] = "1.00";
    root["DevType"] = 17;
    root["DevIP"] = getLocalIPAddress();
    root["Time"] = getCurrentTimeFormatted(); // 动态获取当前时间

    // 使用 StreamWriterBuilder 生成紧凑 JSON 字符串
    Json::StreamWriterBuilder builder;
    builder["indentation"] = "  "; // 紧凑格式（无换行）
    return Json::writeString(builder, root);
}

/**
 * @brief 构建获取阈值参数JSON
 *
 * @return std::string
 */
std::string build_get_threshold_json(void)
{
    Json::Value root;
    root["ProtocolID"] = "1.00";
    root["DevType"] = "C1";
    root["DevIP"] = getLocalIPAddress();      // 获取本机 IP 地址
    root["Time"] = getCurrentTimeFormatted(); // 字段重命名

    // 使用 FastWriter 生成紧凑 JSON（无缩进）
    Json::StreamWriterBuilder builder;
    // builder["indentation"] = ""; // 空字符串表示不换行
    builder["indentation"] = "  "; // 2 spaces
    std::unique_ptr<Json::StreamWriter> writer(builder.newStreamWriter());
    std::ostringstream os;
    writer->write(root, &os);
    return os.str();
}

/**
 * @brief 构建获取设备rsp数量json
 *
 * @return std::string
 */
std::string build_get_rsp_num_json(uint32_t rsp_num)
{
    Json::Value root;
    root["ProtocolID"] = "1.00";
    root["DevType"] = "C1";
    root["DevIP"] = getLocalIPAddress();      // 获取本机 IP 地址
    root["Time"] = getCurrentTimeFormatted(); // 字段重命名
    root["RSPCount"] = rsp_num;

    // 使用 FastWriter 生成紧凑 JSON（无缩进）
    Json::StreamWriterBuilder builder;
    // builder["indentation"] = ""; // 空字符串表示不换行
    builder["indentation"] = "  "; // 2 spaces
    std::unique_ptr<Json::StreamWriter> writer(builder.newStreamWriter());
    std::ostringstream os;
    writer->write(root, &os);
    return os.str();
}

uint32_t rsp_data_status_parse_convert(const Json::Value &item, const int id, DeviceStatus dev_status)
{
    /* ======================= status parse start=============================== */
    // 状态

    uint32_t alpha_status = 0;
    uint32_t beta_status = 0;
    uint32_t gama_status = 0;

    uint32_t new_status = 0;

    // 测量结果的处理，主要是污染的判定
    if (DeviceStatus::FRONT_MEASUREMENT_RESULT == dev_status ||
        DeviceStatus::BACK_MEASUREMENT_RESULT == dev_status)
    {
        // gama status
        if (item.isMember("StaGa") && item["StaGa"].isInt())
        {
            gama_status = static_cast<uint16_t>(item["StaGa"].asInt());
            // 伽马污染判定
            if (PollutionStatus::CONTAMINATED == static_cast<PollutionStatus>(gama_status))
            {
                new_status |= static_cast<uint32_t>(NewDetectorStatus::POLLUTED_GAMMA);
                zlog_info(zlog_get_category(ZLOG_CAG_MQTT), "RSP ID %d has Polluted Gamma", id);
            }
            else if (PollutionStatus::SEVERE_CONTAMINATION == static_cast<PollutionStatus>(gama_status))
            {
                new_status |= static_cast<uint32_t>(NewDetectorStatus::SERIOUSLY_POLLUTED_GAMMA);
                zlog_info(zlog_get_category(ZLOG_CAG_MQTT), "RSP ID %d has Severe Polluted Gamma", id);
            }
            else
            {
                new_status |= static_cast<uint32_t>(NewDetectorStatus::NOT_POLLUTED);
            }
        }
        else
        {
            zlog_warn(zlog_get_category(ZLOG_CAG_MQTT), "RSP ID %d has no Member StaGa", id);
        }

        // alpha status
        if (item.isMember("StaAl") && item["StaAl"].isInt())
        {
            alpha_status = static_cast<uint16_t>(item["StaAl"].asInt());
            // 阿尔法污染判定
            if (PollutionStatus::CONTAMINATED == static_cast<PollutionStatus>(alpha_status))
            {
                new_status |= static_cast<uint32_t>(NewDetectorStatus::POLLUTED_ALPHA);
                zlog_info(zlog_get_category(ZLOG_CAG_MQTT), "RSP ID %d has Polluted Alpha", id);
            }
            else if (PollutionStatus::SEVERE_CONTAMINATION == static_cast<PollutionStatus>(alpha_status))
            {
                new_status |= static_cast<uint32_t>(NewDetectorStatus::SERIOUSLY_POLLUTED_ALPHA);
                zlog_info(zlog_get_category(ZLOG_CAG_MQTT), "RSP ID %d has Severe Polluted Alpha", id);
            }
            else
            {
                new_status |= static_cast<uint32_t>(NewDetectorStatus::NOT_POLLUTED);
            }
        }
        else
        {
            zlog_warn(zlog_get_category(ZLOG_CAG_MQTT), "RSP ID %d has no Member StaAl", id);
        }

        // beta status
        if (item.isMember("StaBe") && item["StaBe"].isInt())
        {
            beta_status = static_cast<uint16_t>(item["StaBe"].asInt());
            // 贝塔污染判定
            if (PollutionStatus::CONTAMINATED == static_cast<PollutionStatus>(beta_status))
            {
                new_status |= static_cast<uint32_t>(NewDetectorStatus::POLLUTED_BETA);
                zlog_info(zlog_get_category(ZLOG_CAG_MQTT), "RSP ID %d has Polluted Beta", id);
            }
            else if (PollutionStatus::SEVERE_CONTAMINATION == static_cast<PollutionStatus>(beta_status))
            {
                new_status |= static_cast<uint32_t>(NewDetectorStatus::SERIOUSLY_POLLUTED_BETA);
                zlog_info(zlog_get_category(ZLOG_CAG_MQTT), "RSP ID %d has Severe Polluted Beta", id);
            }
            else
            {
                new_status |= static_cast<uint32_t>(NewDetectorStatus::NOT_POLLUTED);
            }
        }
        else
        {
            zlog_warn(zlog_get_category(ZLOG_CAG_MQTT), "RSP ID %d has no Member StaBe", id);
        }
    }
    else
    {
        uint16_t status = 0;
        if (item.isMember("Status") && item["Status"].isInt()) // Status
        {
            status = static_cast<uint16_t>(item["Status"].asInt());
            // zlog_info(zlog_get_category(ZLOG_CAG_MQTT), "RSP ID %d  old Status =%d", id, status);
        }
        else
        {
            zlog_warn(zlog_get_category(ZLOG_CAG_MQTT), "RSP ID %d has no Member Status", id);
        }

        if (DetectorStatus::COMMUNICATION_FAULT == static_cast<DetectorStatus>(status))
        {
            new_status |= static_cast<uint32_t>(NewDetectorStatus::COMMUNICATION_FAULT);
        }
        else if (DetectorStatus::LOW_BACKGROUND_FAULT == static_cast<DetectorStatus>(status))
        {
            new_status |= static_cast<uint32_t>(NewDetectorStatus::LOW_BACKGROUND_FAULT);
        }
        else if (DetectorStatus::HIGH_BACKGROUND_FAULT == static_cast<DetectorStatus>(status))
        {
            new_status |= static_cast<uint32_t>(NewDetectorStatus::HIGH_BACKGROUND_FAULT);
        }
        else if (DetectorStatus::HIGH_VOLTAGE_FAULT == static_cast<DetectorStatus>(status))
        {
            new_status |= static_cast<uint32_t>(NewDetectorStatus::HIGH_VOLTAGE_FAULT);
        }
        else if (DetectorStatus::RSP_ADJUSTING_HIGH_VOLTAGE == static_cast<DetectorStatus>(status) ||
                 DetectorStatus::RSP_ADJUSTING_STATE == static_cast<DetectorStatus>(status))
        {
            new_status |= static_cast<uint32_t>(NewDetectorStatus::RSP_ADJUSTING_HV);
        }
        else if (DetectorStatus::RSP_HIGH_VOLTAGE_ERROR == static_cast<DetectorStatus>(status))
        {
            new_status |= static_cast<uint32_t>(NewDetectorStatus::RSP_HV_ERROR_TOO_LARGE);
        }
        else if (DetectorStatus::RSP_NO_RESPONSE == static_cast<DetectorStatus>(status))
        {
            new_status |= static_cast<uint32_t>(NewDetectorStatus::RSP_NO_RESPONSE);
        }
        else if (DetectorStatus::RSP_NOT_USER == static_cast<DetectorStatus>(status))
        {
            new_status |= static_cast<uint32_t>(NewDetectorStatus::RSP_DISABLED);
        }
        else
        {
            new_status |= static_cast<uint32_t>(NewDetectorStatus::MEASURING);
        }
    }
    // zlog_info(zlog_get_category(ZLOG_CAG_MQTT), "RSP ID %d NEW Status=%08x", id, new_status);
    return new_status;
    /* ======================= status parse end =============================== */
}

/**
 * @brief 解析设备rsp数据信息
 *
 * @param json_string
 * @param config
 * @return true
 * @return false
 */
bool parseDetectorData(const std::string &jsonStr, rsp_data_info &info)
{
    Json::Value root;
    Json::CharReaderBuilder builder;
    std::string errs;

    std::istringstream iss(jsonStr);
    if (!parseFromStream(builder, iss, &root, &errs))
    {
        return false;
    }

    try
    {
        // 添加成员存在性检查
        if (root.isMember("ProtocolID") && root["ProtocolID"].isString())
        {
            info.ProtocolID = root["ProtocolID"].asString();
        }
        else
        {
            zlog_warn(zlog_get_category(ZLOG_CAG_MQTT), "ProtocolID is not string or menber not exist");
        }

        if (root.isMember("DevType") && root["DevType"].isInt())
        {
            info.DevType = static_cast<uint16_t>(root["DevType"].asInt());
        }
        else
        {
            zlog_warn(zlog_get_category(ZLOG_CAG_MQTT), "DevType is not int or menber not exist");
        }

        if (root.isMember("DevIP") && root["DevIP"].isString())
        {
            info.DevIP = root["DevIP"].asString();
        }
        else
        {
            zlog_warn(zlog_get_category(ZLOG_CAG_MQTT), "DevIP is not string or menber not exist");
        }

        if (root.isMember("Time") && root["Time"].isString())
        {
            string time_str = root["Time"].asString();
            if (6 != sscanf((char *)time_str.c_str(), "%04u-%02u-%02u %02u:%02u:%02u", info.Time, info.Time + 1, info.Time + 2, info.Time + 3, info.Time + 4, info.Time + 5))
            {
                zlog_warn(zlog_get_category(ZLOG_CAG_MQTT), "parsr time str is fail");
            }
            else
            {
                zlog_info(zlog_get_category(ZLOG_CAG_MQTT), "data time =[%04u-%02u-%02u %02u:%02u:%02u]", info.Time, info.Time + 1, info.Time + 2, info.Time + 3, info.Time + 4, info.Time + 5);
            }
        }
        else
        {
            zlog_warn(zlog_get_category(ZLOG_CAG_MQTT), "Time is not string or menber not exist");
        }

        if (root.isMember("PersonnelID") && root["PersonnelID"].isString())
        {
            info.PersonnelID = root["PersonnelID"].asString();
        }
        else
        {
            zlog_warn(zlog_get_category(ZLOG_CAG_MQTT), "PersonnelID is not string or menber not exist");
        }

        if (root.isMember("RSPCount") && root["RSPCount"].isInt())
        {
            info.RSPCount = static_cast<uint16_t>(root["RSPCount"].asInt());
        }
        else
        {
            zlog_warn(zlog_get_category(ZLOG_CAG_MQTT), "RSPCount is not int or menber not exist");
        }

        // 推理设备类型
        if (10 == info.RSPCount)
        {
            get_dev_data_ptr()->reg_dev_type = DEV::DOOR_C1;
        }
        else if (25 >= info.RSPCount)
        {
            get_dev_data_ptr()->reg_dev_type = DEV::DOOR_C2;
        }
        else
        {
            get_dev_data_ptr()->reg_dev_type = get_app_config_ptr()->cfg.dev_type_code;
            zlog_warn(zlog_get_category(ZLOG_CAG_MQTT), "Failure to infer device type");
        }
        zlog_info(zlog_get_category(ZLOG_CAG_MQTT), "RSPCount %d, reg_dev_type %d", info.RSPCount, get_dev_data_ptr()->reg_dev_type);

        if (root.isMember("DevStatus") && root["DevStatus"].isInt())
        {
            info.reg_status = root["DevStatus"].asInt();
        }
        else
        {
            zlog_warn(zlog_get_category(ZLOG_CAG_MQTT), "DevStatus is not int or menber not exist");
        }

        info.RSPUseBit = 0;
        memset(info.reg_rsp_status, 0, sizeof(info.reg_rsp_status));
        memset(info.reg_rsp_alpha_valt, 0, sizeof(info.reg_rsp_alpha_valt));
        memset(info.reg_rsp_bate_valt, 0, sizeof(info.reg_rsp_bate_valt));
        memset(info.reg_rsp_gama_valt, 0, sizeof(info.reg_rsp_gama_valt));

        // 填充 RSPData 数组
        int id_max = 0;
        if (root.isMember("RSPData") && root["RSPData"].isArray())
        {
            const Json::Value &rspArray = root["RSPData"];
            for (const auto &item : rspArray)
            {
                if (item.isMember("ID") && item["ID"].isInt())
                {
                    int id = item["ID"].asInt();
                    id_max = std::max(id_max, id);
                    if (id < 1 || id > MAX_RSP_NUM)
                    {
                        zlog_warn(zlog_get_category(ZLOG_CAG_MQTT), "RSP ID %d is out of range", id);
                        continue; // 越界检查
                    }

                    int idx = id - 1; // 转为数组下标

                    if (idx >= info.RSPCount)
                    {
                        zlog_warn(zlog_get_category(ZLOG_CAG_MQTT), "RSP index %d is out of range[0-%d]", id, info.RSPCount);
                        continue;
                    }

                    // rsp使用了那些bit
                    info.RSPUseBit |= (1 << idx);
                    // 状态
                    info.reg_rsp_status[idx] = rsp_data_status_parse_convert(item, id, static_cast<DeviceStatus>(info.reg_status));
                    // 伽马
                    if (item.isMember("GammaValue") && item["GammaValue"].isDouble())
                    {
                        info.reg_rsp_gama_valt[idx] = static_cast<float>(item["GammaValue"].asFloat());
                    }
                    else
                    {
                        zlog_warn(zlog_get_category(ZLOG_CAG_MQTT), "RSP ID %d has no Member GammaValue", id);
                    }
                    // alpha
                    if (item.isMember("AlphaValue") && item["AlphaValue"].isDouble())
                    {
                        info.reg_rsp_alpha_valt[idx] = static_cast<float>(item["AlphaValue"].asFloat());
                    }
                    else
                    {
                        zlog_warn(zlog_get_category(ZLOG_CAG_MQTT), "RSP ID %d has no Member AlphaValue", id);
                    }
                    // beta
                    if (item.isMember("BetaValue") && item["BetaValue"].isDouble())
                    {
                        info.reg_rsp_bate_valt[idx] = static_cast<float>(item["BetaValue"].asFloat());
                    }
                    else
                    {
                        zlog_warn(zlog_get_category(ZLOG_CAG_MQTT), "RSP ID %d has no Member BetaValue", id);
                    }
                }
                else
                {
                    zlog_warn(zlog_get_category(ZLOG_CAG_MQTT), "RSPData item has no Member ID");
                }
            }
        }
        else
        {
            zlog_warn(zlog_get_category(ZLOG_CAG_MQTT), "RSPData  item is not an array");
        }
    }
    catch (const std::exception &e)
    {
        zlog_warn(zlog_get_category(ZLOG_CAG_MQTT), "json parse error");
        return false;
    }

    return true;
}